package com.lp.multi.thread.example02;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

import static java.util.concurrent.Executors.*;

/**
 * @author: lp
 * @create: 2021-06-21 10:26
 * @description: 实现Callable接口,使用线程池执行任务
 */
public class CallableThread implements Callable<Boolean>{
    private String urlpath;
    private String downloadPath;

    public CallableThread(String urlpath,String downloadPath){
        this.urlpath = urlpath;
        this.downloadPath = downloadPath;
    }



    @Override
    public Boolean call() {
        DownLoadUtil downLoadUtil = new DownLoadUtil();
        downLoadUtil.downLoad(urlpath,downloadPath);
        System.out.println("下载了文件"+downloadPath);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CallableThread Thread01 = new CallableThread("https://www.baidu.com/img/flexible/logo/pc/result.png", "result.png");
        CallableThread Thread02 = new CallableThread("https://www.baidu.com/img/flexible/logo/pc/peak-result.png", "result2.png");
        CallableThread Thread03 = new CallableThread("https://www.baidu.com/img/flexible/logo/pc/result@2.png", "result3.png");
        //1.开启线程池
        ExecutorService threadPool = newFixedThreadPool(3);
        //2.向线程池提交执行线程任务
        Future<Boolean> thread01Result = threadPool.submit(Thread01);
        Future<Boolean> thread02Result = threadPool.submit(Thread02);
        Future<Boolean> thread03Result = threadPool.submit(Thread03);
        //3.获取线程任务返回结果
        System.out.println(thread01Result.get());
        System.out.println(thread02Result.get());
        System.out.println(thread03Result.get());
        //4.关闭线程池
        threadPool.shutdown();
    }
}

class DownLoadUtil{
    public void downLoad(String urlpath,String downloadPath){
        try {
            FileUtils.copyURLToFile(new URL(urlpath),new File(downloadPath));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常，下载失败!");
        }
    }
}

